using DocumentCreationSystem.Models;
using Microsoft.Extensions.Logging;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;

namespace DocumentCreationSystem.Services;

/// <summary>
/// 思维链处理服务实现
/// </summary>
public class ThinkingChainService : IThinkingChainService
{
    private readonly ILogger<ThinkingChainService> _logger;
    private ThinkingChainDisplayConfig _displayConfig;
    private ThinkingChainStatistics _statistics;
    private readonly List<ThinkingChainResponse> _processedResponses;

    // 思维链标记模式 - 支持多种格式
    private static readonly Regex ThinkingChainPattern = new(@"<thinking>(.*?)</thinking>", RegexOptions.Singleline | RegexOptions.IgnoreCase);
    private static readonly Regex ThinkChainPattern = new(@"<think>(.*?)</think>", RegexOptions.Singleline | RegexOptions.IgnoreCase);
    private static readonly Regex QwenThinkPattern = new(@"(.*?)</think>", RegexOptions.Singleline | RegexOptions.IgnoreCase);
    private static readonly Regex OutputPattern = new(@"<output>(.*?)</output>", RegexOptions.Singleline | RegexOptions.IgnoreCase);
    private static readonly Regex OutputTagPattern = new(@"<output>(.*?)</output>", RegexOptions.Singleline | RegexOptions.IgnoreCase);
    private static readonly Regex ThinkingStepPattern = new(@"(?:步骤|Step)\s*(\d+)[：:]\s*(.*?)(?=(?:步骤|Step)\s*\d+[：:]|$)", RegexOptions.Singleline | RegexOptions.IgnoreCase);
    private static readonly Regex KeyStepPattern = new(@"(?:关键|重要|Key|Important)[：:]?\s*(.*?)(?=\n|$)", RegexOptions.IgnoreCase);

    public ThinkingChainService(ILogger<ThinkingChainService> logger)
    {
        _logger = logger;
        _displayConfig = new ThinkingChainDisplayConfig();
        _statistics = new ThinkingChainStatistics();
        _processedResponses = new List<ThinkingChainResponse>();
    }

    public ThinkingChainResponse ParseThinkingChainResponse(string rawContent)
    {
        try
        {
            var response = new ThinkingChainResponse
            {
                RawContent = rawContent
            };

            // 优先检测 <output>...</output> 格式
            var outputTagMatch = OutputTagPattern.Match(rawContent);
            if (outputTagMatch.Success)
            {
                response.FinalOutput = outputTagMatch.Groups[1].Value.Trim();

                // 检测各种思维链格式
                var thinkMatch = ThinkChainPattern.Match(rawContent);
                var thinkingMatch = ThinkingChainPattern.Match(rawContent);
                var qwenMatch = QwenThinkPattern.Match(rawContent);

                if (thinkMatch.Success)
                {
                    response.HasThinkingChain = true;
                    response.ThinkingChain = thinkMatch.Groups[1].Value.Trim();
                    response.ThinkingSteps = ParseThinkingSteps(response.ThinkingChain);
                }
                else if (thinkingMatch.Success)
                {
                    response.HasThinkingChain = true;
                    response.ThinkingChain = thinkingMatch.Groups[1].Value.Trim();
                    response.ThinkingSteps = ParseThinkingSteps(response.ThinkingChain);
                }
                else if (qwenMatch.Success)
                {
                    response.HasThinkingChain = true;
                    response.ThinkingChain = qwenMatch.Groups[1].Value.Trim();
                    response.ThinkingSteps = ParseThinkingSteps(response.ThinkingChain);
                }

                return response;
            }

            // 优先检测 <output>...</output> 格式
            var outputMatch = OutputPattern.Match(rawContent);
            if (outputMatch.Success)
            {
                response.FinalOutput = outputMatch.Groups[1].Value.Trim();

                // 检测 <think>...</think> 格式的思维链
                var thinkMatch = ThinkChainPattern.Match(rawContent);
                if (thinkMatch.Success)
                {
                    response.HasThinkingChain = true;
                    response.ThinkingChain = thinkMatch.Groups[1].Value.Trim();
                    response.ThinkingSteps = ParseThinkingSteps(response.ThinkingChain);
                }
                else
                {
                    // 检测 <thinking>...</thinking> 格式的思维链
                    var thinkingMatch = ThinkingChainPattern.Match(rawContent);
                    if (thinkingMatch.Success)
                    {
                        response.HasThinkingChain = true;
                        response.ThinkingChain = thinkingMatch.Groups[1].Value.Trim();
                        response.ThinkingSteps = ParseThinkingSteps(response.ThinkingChain);
                    }
                    else
                    {
                        // 检测 Qwen 格式的思维链 (...</think>)
                        var qwenMatch = QwenThinkPattern.Match(rawContent);
                        if (qwenMatch.Success)
                        {
                            response.HasThinkingChain = true;
                            response.ThinkingChain = qwenMatch.Groups[1].Value.Trim();
                            response.ThinkingSteps = ParseThinkingSteps(response.ThinkingChain);
                        }
                    }
                }
            }
            else
            {
                // 兼容旧格式：检测 <thinking>...</thinking> 或 <think>...</think> 或 ...</think>
                var thinkingMatch = ThinkingChainPattern.Match(rawContent);
                var thinkMatch = ThinkChainPattern.Match(rawContent);
                var qwenMatch = QwenThinkPattern.Match(rawContent);

                if (thinkingMatch.Success)
                {
                    response.HasThinkingChain = true;
                    response.ThinkingChain = thinkingMatch.Groups[1].Value.Trim();
                    response.FinalOutput = ThinkingChainPattern.Replace(rawContent, "").Trim();
                    response.ThinkingSteps = ParseThinkingSteps(response.ThinkingChain);
                }
                else if (thinkMatch.Success)
                {
                    response.HasThinkingChain = true;
                    response.ThinkingChain = thinkMatch.Groups[1].Value.Trim();
                    response.FinalOutput = ThinkChainPattern.Replace(rawContent, "").Trim();
                    response.ThinkingSteps = ParseThinkingSteps(response.ThinkingChain);
                }
                else if (qwenMatch.Success)
                {
                    response.HasThinkingChain = true;
                    response.ThinkingChain = qwenMatch.Groups[1].Value.Trim();
                    response.FinalOutput = QwenThinkPattern.Replace(rawContent, "").Trim();
                    response.ThinkingSteps = ParseThinkingSteps(response.ThinkingChain);
                }
                else
                {
                    // 尝试其他模式检测
                    response.HasThinkingChain = DetectImplicitThinkingChain(rawContent, response);
                    if (!response.HasThinkingChain)
                    {
                        response.FinalOutput = rawContent;
                    }
                }
            }

            // 更新统计信息
            UpdateStatistics(response);

            return response;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "解析思维链响应时发生错误");
            return new ThinkingChainResponse
            {
                RawContent = rawContent,
                FinalOutput = rawContent,
                HasThinkingChain = false
            };
        }
    }

    private List<ThinkingStep> ParseThinkingSteps(string thinkingContent)
    {
        var steps = new List<ThinkingStep>();
        
        // 按步骤分割
        var stepMatches = ThinkingStepPattern.Matches(thinkingContent);
        
        if (stepMatches.Count > 0)
        {
            foreach (Match match in stepMatches)
            {
                if (int.TryParse(match.Groups[1].Value, out var stepNumber))
                {
                    var content = match.Groups[2].Value.Trim();
                    var isKeyStep = KeyStepPattern.IsMatch(content);
                    
                    steps.Add(new ThinkingStep
                    {
                        StepNumber = stepNumber,
                        Content = content,
                        IsKeyStep = isKeyStep,
                        StepType = DetermineStepType(content)
                    });
                }
            }
        }
        else
        {
            // 如果没有明确的步骤标记，按段落分割
            var paragraphs = thinkingContent.Split('\n', StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < paragraphs.Length; i++)
            {
                var paragraph = paragraphs[i].Trim();
                if (!string.IsNullOrEmpty(paragraph))
                {
                    steps.Add(new ThinkingStep
                    {
                        StepNumber = i + 1,
                        Content = paragraph,
                        IsKeyStep = KeyStepPattern.IsMatch(paragraph),
                        StepType = DetermineStepType(paragraph)
                    });
                }
            }
        }

        return steps;
    }

    private bool DetectImplicitThinkingChain(string content, ThinkingChainResponse response)
    {
        // 检测隐式思维链模式
        var patterns = new[]
        {
            // 思考过程开头的内容
            @"思考过程[：:]?\s*(.*?)(?=\n\n接下来生成|<o>|$)",
            @"思考过程[：:]?\s*(.*?)(?=\n\n|$)",

            // 格式说明内容（完整匹配）
            @"1\.\s*如果需要思考过程.*?(?=<o>|$)",
            @"2\.\s*将最终答案放在.*?(?=<o>|$)",
            @"3\.\s*只有.*?标签中的内容.*?(?=<o>|$)",
            @"4\.\s*支持多种思维链格式.*?(?=<o>|$)",
            @"示例格式[：:]?\s*<o>\s*这里是最终的回答内容\s*</o>",
            @"（此处为思考过程的占位.*?(?=<o>|$)",

            // 接下来生成提示
            @"接下来生成最终章节内容.*?(?=<o>|$)",

            // 其他思维链模式
            @"让我想想[：:]?(.*?)(?=\n\n|\n[^让我想想]|$)",
            @"首先[：:]?(.*?)其次[：:]?(.*?)(?:最后|最终)[：:]?(.*?)(?=\n\n|$)",
            @"分析[：:]?(.*?)结论[：:]?(.*?)(?=\n\n|$)",
            @"思考[：:]?(.*?)(?=\n\n|\n[^思考]|$)",

            // 分析步骤内容
            @"具体分析步骤如下[：:]?\s*(.*?)(?=\n\n接下来生成|<o>|$)",
            @"分析用户需求.*?(?=\n\n接下来生成|<o>|$)"
        };

        var foundThinking = false;
        var thinkingParts = new List<string>();
        var finalContent = content;

        foreach (var pattern in patterns)
        {
            var matches = Regex.Matches(content, pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase);
            if (matches.Count > 0)
            {
                foundThinking = true;
                foreach (Match match in matches)
                {
                    thinkingParts.Add(match.Value);
                    finalContent = finalContent.Replace(match.Value, "");
                }
            }
        }

        if (foundThinking)
        {
            response.ThinkingChain = string.Join("\n\n", thinkingParts);
            response.FinalOutput = finalContent.Trim();
            response.ThinkingSteps = ParseThinkingSteps(response.ThinkingChain);
            return true;
        }

        return false;
    }

    /// <summary>
    /// 过滤章节内容中的非小说正文部分
    /// </summary>
    public string FilterChapterContent(string content)
    {
        if (string.IsNullOrEmpty(content))
            return content;

        var filteredContent = content;

        // 首先移除所有思维链和输出标签
        filteredContent = RemoveAllThinkingChainTags(filteredContent);

        // 移除AI内部推理过程
        filteredContent = RemoveAIInternalProcessing(filteredContent);

        // 移除章节分析和结构说明
        var nonFictionPatterns = new[]
        {
            // 思考过程和分析
            @"1\.\s*思考过程[：:]?.*?(?=\n\n|2\.|$)",
            @"2\.\s*最终答案[：:]?.*?(?=\n\n|<o>|$)",
            @"思考过程[：:]?\s*.*?(?=\n\n最终答案|<o>|$)",
            @"分析用户需求.*?(?=\n\n|<o>|$)",
            @"具体分析步骤如下[：:]?\s*.*?(?=\n\n|<o>|$)",
            @"接下来生成.*?(?=\n\n|<o>|$)",

            // 章节核心亮点
            @"###?\s*[一二三四五六七八九十]?[、\.]?\s*chapter\s*核心亮点.*?(?=###|$)",
            @"###?\s*本章核心亮点.*?(?=###|$)",
            @"###?\s*核心亮点.*?(?=###|$)",
            @"\*\*本章核心亮点\*\*.*?(?=\*\*|$)",

            // 场景与氛围
            @"###?\s*[一二三四五六七八九十]?[、\.]?\s*场景与氛围.*?(?=###|$)",
            @"\*\*场景与氛围\*\*.*?(?=\*\*|$)",

            // 人物动态
            @"###?\s*[一二三四五六七八九十]?[、\.]?\s*人物动态.*?(?=###|$)",
            @"\*\*人物动态\*\*.*?(?=\*\*|$)",

            // 剧情发展
            @"###?\s*[一二三四五六七八九十]?[、\.]?\s*剧情发展.*?(?=###|$)",
            @"\*\*剧情发展\*\*.*?(?=\*\*|$)",

            // 世界观与伏笔
            @"###?\s*[一二三四五六七八九十]?[、\.]?\s*世界观与伏笔.*?(?=###|$)",
            @"###?\s*世界元素运用.*?(?=###|$)",
            @"\*\*世界元素运用\*\*.*?(?=\*\*|$)",
            @"\*\*世界元素\*\*.*?(?=\*\*|$)",

            // 结尾与过渡
            @"###?\s*[一二三四五六七八九十]?[、\.]?\s*结尾与过渡.*?(?=###|$)",

            // 预期结果
            @"###?\s*预期结果.*?(?=###|$)",
            @"\*\*预期结果\*\*.*?(?=\*\*|$)",

            // 注释和说明
            @"\(注：.*?\)",
            @"（注：.*?）",
            @"\*\*（此处省略.*?\)\*\*",
            @"（此处省略.*?）",

            // 亮点列表
            @"-\s*独特场景[：:].*?(?=\n-|\n\n|$)",
            @"-\s*核心冲突[：:].*?(?=\n-|\n\n|$)",
            @"-\s*人物发展[：:].*?(?=\n-|\n\n|$)",
            @"-\s*读者期待[：:].*?(?=\n-|\n\n|$)",

            // 其他分析内容
            @"主要场景[：:].*?(?=\n\n|$)",
            @"时间点[：:].*?(?=\n\n|$)",
            @"氛围营造[：:].*?(?=\n\n|$)",
            @"主角表现[：:].*?(?=\n\n|$)",
            @"重要角色[：:].*?(?=\n\n|$)",
            @"关系变化[：:].*?(?=\n\n|$)",
            @"起始情境[：:].*?(?=\n\n|$)",
            @"情节推进[：:].*?(?=\n\n|$)",
            @"高潮设计[：:].*?(?=\n\n|$)",
            @"结尾铺垫[：:].*?(?=\n\n|$)",
            @"设定展现[：:].*?(?=\n\n|$)",
            @"伏笔安排[：:].*?(?=\n\n|$)",
            @"角色成长[：:].*?(?=\n\n|$)",
            @"伏笔铺设[：:].*?(?=\n\n|$)",
            @"章节结尾[：:].*?(?=\n\n|$)",

            // 错误信息和占位符
            @"由于您提供的.*?缺少具体的情节描述.*?请您补充完整章节的相关信息后再提出请求。",
            @"<\|begin_of_box\|>.*?<\|end_of_box\|>",
            @"（此处为完整的第.*?章小说章节内容.*?）"
        };

        foreach (var pattern in nonFictionPatterns)
        {
            filteredContent = Regex.Replace(filteredContent, pattern, "", RegexOptions.Singleline | RegexOptions.IgnoreCase);
        }

        // 清理多余的空行
        filteredContent = Regex.Replace(filteredContent, @"\n\s*\n\s*\n", "\n\n", RegexOptions.Multiline);

        return filteredContent.Trim();
    }

    /// <summary>
    /// 移除所有思维链和输出标签
    /// </summary>
    private string RemoveAllThinkingChainTags(string content)
    {
        // 移除所有可能的思维链标签
        var patterns = new[]
        {
            @"<thinking>.*?</thinking>",
            @"<think>.*?</think>",
            @"<o>(.*?)</o>",
            @"<output>(.*?)</output>"
        };

        var result = content;
        foreach (var pattern in patterns)
        {
            var matches = Regex.Matches(result, pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase);
            foreach (Match match in matches)
            {
                if (pattern.Contains("(.*?)") && (pattern.Contains("<o>") || pattern.Contains("<output>")))
                {
                    // 对于输出标签，保留内容但移除标签
                    result = result.Replace(match.Value, match.Groups[1].Value);
                }
                else
                {
                    // 对于思维链标签，完全移除
                    result = result.Replace(match.Value, "");
                }
            }
        }

        return result;
    }

    /// <summary>
    /// 移除AI内部推理过程
    /// </summary>
    private string RemoveAIInternalProcessing(string content)
    {
        var patterns = new[]
        {
            @"1\.\s*思考过程[：:]?.*?(?=2\.|$)",
            @"2\.\s*最终答案[：:]?.*?(?=<o>|$)",
            @"思考过程[：:]?\s*.*?(?=最终答案|<o>|$)",
            @"分析用户需求.*?(?=<o>|$)",
            @"首先明确核心要素.*?(?=<o>|$)",
            @"然后结合上下文.*?(?=<o>|$)",
            @"具体分析步骤如下.*?(?=<o>|$)",
            @"接下来生成.*?(?=<o>|$)"
        };

        var result = content;
        foreach (var pattern in patterns)
        {
            result = Regex.Replace(result, pattern, "", RegexOptions.Singleline | RegexOptions.IgnoreCase);
        }

        return result;
    }

    private string DetermineStepType(string content)
    {
        var lowerContent = content.ToLower();
        
        if (lowerContent.Contains("分析") || lowerContent.Contains("analyze"))
            return "分析";
        if (lowerContent.Contains("推理") || lowerContent.Contains("reason"))
            return "推理";
        if (lowerContent.Contains("总结") || lowerContent.Contains("summary"))
            return "总结";
        if (lowerContent.Contains("结论") || lowerContent.Contains("conclusion"))
            return "结论";
        if (lowerContent.Contains("假设") || lowerContent.Contains("assume"))
            return "假设";
        if (lowerContent.Contains("验证") || lowerContent.Contains("verify"))
            return "验证";
        
        return "思考";
    }

    /// <summary>
    /// 简单的思维链过滤方法，直接处理字符串内容
    /// </summary>
    public string FilterThinkingChain(string content)
    {
        if (string.IsNullOrEmpty(content))
            return content;

        var filteredContent = content;

        // 移除所有思维链标签及其内容
        var thinkingPatterns = new[]
        {
            @"<thinking>.*?</thinking>",
            @"<think>.*?</think>",
            @"<reasoning>.*?</reasoning>",
            @"<analysis>.*?</analysis>"
        };

        foreach (var pattern in thinkingPatterns)
        {
            filteredContent = Regex.Replace(filteredContent, pattern, "", RegexOptions.Singleline | RegexOptions.IgnoreCase);
        }

        // 提取输出标签内的内容
        var outputPatterns = new[]
        {
            @"<output>(.*?)</output>",
            @"<o>(.*?)</o>",
            @"<result>(.*?)</result>",
            @"<answer>(.*?)</answer>"
        };

        foreach (var pattern in outputPatterns)
        {
            var match = Regex.Match(filteredContent, pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase);
            if (match.Success)
            {
                filteredContent = match.Groups[1].Value;
                break; // 找到第一个匹配的输出标签就停止
            }
        }

        // 移除AI内部推理标识
        var internalProcessingPatterns = new[]
        {
            @"1\.\s*思考过程[：:]?.*?(?=2\.|$)",
            @"2\.\s*最终答案[：:]?.*?(?=\n\n|$)",
            @"思考过程[：:]?\s*.*?(?=最终答案|\n\n|$)",
            @"分析用户需求.*?(?=\n\n|$)",
            @"具体分析步骤如下.*?(?=\n\n|$)",
            @"接下来生成.*?(?=\n\n|$)",
            @"首先明确核心要素.*?(?=\n\n|$)",
            @"然后结合上下文.*?(?=\n\n|$)"
        };

        foreach (var pattern in internalProcessingPatterns)
        {
            filteredContent = Regex.Replace(filteredContent, pattern, "", RegexOptions.Singleline | RegexOptions.IgnoreCase);
        }

        // 移除残留的标签
        var residualTags = new[]
        {
            @"</?thinking>",
            @"</?think>",
            @"</?output>",
            @"</?o>",
            @"</?result>",
            @"</?answer>",
            @"</?reasoning>",
            @"</?analysis>"
        };

        foreach (var tag in residualTags)
        {
            filteredContent = Regex.Replace(filteredContent, tag, "", RegexOptions.IgnoreCase);
        }

        // 清理多余的空行和空白字符
        filteredContent = Regex.Replace(filteredContent, @"\n\s*\n\s*\n", "\n\n", RegexOptions.Multiline);
        filteredContent = Regex.Replace(filteredContent, @"^\s+", "", RegexOptions.Multiline);

        return filteredContent.Trim();
    }

    public string FilterThinkingChain(ThinkingChainResponse response, ThinkingChainFilter filter)
    {
        if (!filter.EnableFilter || !response.HasThinkingChain)
        {
            return response.RawContent;
        }

        return filter.Mode switch
        {
            FilterMode.RemoveThinkingChain => response.FinalOutput,
            FilterMode.HideThinkingChain => AddHiddenThinkingChainMarker(response),
            FilterMode.CompressToSummary => CompressThinkingChainToSummary(response, filter),
            FilterMode.KeyStepsOnly => ExtractKeyStepsOnly(response),
            _ => response.FinalOutput
        };
    }

    private string AddHiddenThinkingChainMarker(ThinkingChainResponse response)
    {
        var marker = "<!-- 思维链内容已隐藏 -->";
        return $"{response.FinalOutput}\n\n{marker}";
    }

    private string CompressThinkingChainToSummary(ThinkingChainResponse response, ThinkingChainFilter filter)
    {
        var summary = GenerateThinkingChainSummary(response);
        
        if (filter.AddSummary)
        {
            return $"{response.FinalOutput}\n\n**思维过程摘要：**\n{summary}";
        }
        
        return response.FinalOutput;
    }

    private string ExtractKeyStepsOnly(ThinkingChainResponse response)
    {
        var keySteps = response.ThinkingSteps.Where(s => s.IsKeyStep).ToList();
        
        if (keySteps.Any())
        {
            var keyStepsText = string.Join("\n", keySteps.Select(s => $"• {s.Content}"));
            return $"{response.FinalOutput}\n\n**关键思考步骤：**\n{keyStepsText}";
        }
        
        return response.FinalOutput;
    }

    public ThinkingChainProcessResult ProcessThinkingChainResponse(string rawContent, ThinkingChainFilter? filter = null)
    {
        try
        {
            var response = ParseThinkingChainResponse(rawContent);
            var defaultFilter = filter ?? new ThinkingChainFilter();
            
            var processedContent = FilterThinkingChain(response, defaultFilter);
            
            _processedResponses.Add(response);
            
            return new ThinkingChainProcessResult
            {
                ProcessedContent = processedContent,
                OriginalResponse = response,
                Status = ProcessStatus.Success,
                Message = "处理成功",
                ContainsThinkingChain = response.HasThinkingChain,
                ThinkingStepsCount = response.ThinkingSteps.Count
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "处理思维链响应时发生错误");
            return new ThinkingChainProcessResult
            {
                ProcessedContent = rawContent,
                Status = ProcessStatus.Error,
                Message = $"处理失败: {ex.Message}",
                ContainsThinkingChain = false,
                ThinkingStepsCount = 0
            };
        }
    }

    public string GenerateThinkingChainSummary(ThinkingChainResponse response)
    {
        if (!response.HasThinkingChain || !response.ThinkingSteps.Any())
        {
            return "无思维链内容";
        }

        var summary = new StringBuilder();
        var keySteps = response.ThinkingSteps.Where(s => s.IsKeyStep).ToList();
        
        if (keySteps.Any())
        {
            summary.AppendLine("关键思考步骤：");
            foreach (var step in keySteps.Take(3)) // 最多显示3个关键步骤
            {
                summary.AppendLine($"• {step.Content.Substring(0, Math.Min(100, step.Content.Length))}...");
            }
        }
        else
        {
            summary.AppendLine($"共{response.ThinkingSteps.Count}个思考步骤，");
            summary.AppendLine($"主要涉及{string.Join("、", response.ThinkingSteps.Select(s => s.StepType).Distinct())}");
        }

        return summary.ToString().Trim();
    }

    public string FormatThinkingChainDisplay(ThinkingChainResponse response, ThinkingChainDisplayConfig config)
    {
        if (!response.HasThinkingChain || config.DisplayStyle == ThinkingChainStyle.Hidden)
        {
            return response.FinalOutput;
        }

        var display = new StringBuilder();
        display.AppendLine(response.FinalOutput);

        if (config.ShowThinkingChain)
        {
            display.AppendLine();

            switch (config.DisplayStyle)
            {
                case ThinkingChainStyle.Expandable:
                    display.AppendLine(FormatExpandableThinkingChain(response, config));
                    break;
                case ThinkingChainStyle.Inline:
                    display.AppendLine(FormatInlineThinkingChain(response, config));
                    break;
                case ThinkingChainStyle.Sidebar:
                    display.AppendLine(FormatSidebarThinkingChain(response, config));
                    break;
                case ThinkingChainStyle.Modal:
                    display.AppendLine(FormatModalThinkingChain(response, config));
                    break;
            }
        }

        return display.ToString().Trim();
    }

    private string FormatExpandableThinkingChain(ThinkingChainResponse response, ThinkingChainDisplayConfig config)
    {
        var result = new StringBuilder();
        var stepsToShow = config.MaxDisplaySteps > 0
            ? response.ThinkingSteps.Take(config.MaxDisplaySteps)
            : response.ThinkingSteps;

        result.AppendLine(config.IsCollapsed ? "▶ 思维过程 (点击展开)" : "▼ 思维过程");

        if (!config.IsCollapsed)
        {
            foreach (var step in stepsToShow)
            {
                var prefix = config.ShowStepNumbers ? $"{step.StepNumber}. " : "• ";
                var highlight = config.HighlightKeySteps && step.IsKeyStep ? "**" : "";

                result.AppendLine($"  {prefix}{highlight}{step.Content}{highlight}");
            }
        }

        return result.ToString();
    }

    private string FormatInlineThinkingChain(ThinkingChainResponse response, ThinkingChainDisplayConfig config)
    {
        var result = new StringBuilder();
        result.AppendLine("---");
        result.AppendLine("**思维过程：**");

        var stepsToShow = config.MaxDisplaySteps > 0
            ? response.ThinkingSteps.Take(config.MaxDisplaySteps)
            : response.ThinkingSteps;

        foreach (var step in stepsToShow)
        {
            var prefix = config.ShowStepNumbers ? $"{step.StepNumber}. " : "• ";
            var highlight = config.HighlightKeySteps && step.IsKeyStep ? "**" : "";

            result.AppendLine($"{prefix}{highlight}{step.Content}{highlight}");
        }

        result.AppendLine("---");
        return result.ToString();
    }

    private string FormatSidebarThinkingChain(ThinkingChainResponse response, ThinkingChainDisplayConfig config)
    {
        // 侧边栏格式（简化版本）
        var summary = GenerateThinkingChainSummary(response);
        return $"[思维链] {summary}";
    }

    private string FormatModalThinkingChain(ThinkingChainResponse response, ThinkingChainDisplayConfig config)
    {
        // 弹窗格式（简化版本）
        return "[点击查看思维过程]";
    }

    public bool ContainsThinkingChain(string content)
    {
        if (string.IsNullOrEmpty(content))
            return false;

        // 检查明确的思维链标记 - 支持多种格式
        if (ThinkingChainPattern.IsMatch(content) || ThinkChainPattern.IsMatch(content) || QwenThinkPattern.IsMatch(content))
            return true;

        // 检查是否包含输出标签（可能包含思维链）
        if (OutputPattern.IsMatch(content) || OutputTagPattern.IsMatch(content))
        {
            // 如果有输出标签，检查是否同时包含思维链
            return ThinkingChainPattern.IsMatch(content) || ThinkChainPattern.IsMatch(content) || QwenThinkPattern.IsMatch(content);
        }

        // 检查隐式思维链模式
        var implicitPatterns = new[]
        {
            @"让我想想",
            @"首先.*?其次.*?最后",
            @"分析.*?结论",
            @"思考.*?总结"
        };

        return implicitPatterns.Any(pattern =>
            Regex.IsMatch(content, pattern, RegexOptions.IgnoreCase));
    }

    public ThinkingChainStatistics GetStatistics()
    {
        return _statistics;
    }

    public void ResetStatistics()
    {
        _statistics = new ThinkingChainStatistics();
        _processedResponses.Clear();
    }

    public void UpdateDisplayConfig(ThinkingChainDisplayConfig config)
    {
        _displayConfig = config ?? new ThinkingChainDisplayConfig();
    }

    public ThinkingChainDisplayConfig GetDisplayConfig()
    {
        return _displayConfig;
    }

    public string ExportThinkingChainData(List<ThinkingChainResponse> responses, string format = "json")
    {
        try
        {
            return format.ToLower() switch
            {
                "json" => JsonSerializer.Serialize(responses, new JsonSerializerOptions { WriteIndented = true }),
                "csv" => ExportToCsv(responses),
                "txt" => ExportToText(responses),
                _ => JsonSerializer.Serialize(responses, new JsonSerializerOptions { WriteIndented = true })
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "导出思维链数据时发生错误");
            return $"导出失败: {ex.Message}";
        }
    }

    private string ExportToCsv(List<ThinkingChainResponse> responses)
    {
        var csv = new StringBuilder();
        csv.AppendLine("序号,包含思维链,思维链步骤数,最终输出长度,处理时间");

        for (int i = 0; i < responses.Count; i++)
        {
            var response = responses[i];
            csv.AppendLine($"{i + 1},{response.HasThinkingChain},{response.ThinkingSteps.Count},{response.FinalOutput.Length},{DateTime.Now:yyyy-MM-dd HH:mm:ss}");
        }

        return csv.ToString();
    }

    private string ExportToText(List<ThinkingChainResponse> responses)
    {
        var text = new StringBuilder();
        text.AppendLine("思维链数据导出");
        text.AppendLine("================");
        text.AppendLine();

        for (int i = 0; i < responses.Count; i++)
        {
            var response = responses[i];
            text.AppendLine($"响应 {i + 1}:");
            text.AppendLine($"包含思维链: {response.HasThinkingChain}");
            text.AppendLine($"思维链步骤数: {response.ThinkingSteps.Count}");
            text.AppendLine($"最终输出: {response.FinalOutput.Substring(0, Math.Min(200, response.FinalOutput.Length))}...");
            text.AppendLine();
        }

        return text.ToString();
    }

    public Dictionary<string, object> AnalyzeThinkingChainPatterns(List<ThinkingChainResponse> responses)
    {
        var analysis = new Dictionary<string, object>();

        if (!responses.Any())
        {
            analysis["message"] = "没有数据可分析";
            return analysis;
        }

        var withThinkingChain = responses.Where(r => r.HasThinkingChain).ToList();

        analysis["总响应数"] = responses.Count;
        analysis["包含思维链的响应数"] = withThinkingChain.Count;
        analysis["思维链使用率"] = withThinkingChain.Count / (float)responses.Count * 100;

        if (withThinkingChain.Any())
        {
            analysis["平均思维链步骤数"] = withThinkingChain.Average(r => r.ThinkingSteps.Count);
            analysis["最大思维链步骤数"] = withThinkingChain.Max(r => r.ThinkingSteps.Count);
            analysis["最小思维链步骤数"] = withThinkingChain.Min(r => r.ThinkingSteps.Count);

            var stepTypes = withThinkingChain
                .SelectMany(r => r.ThinkingSteps)
                .GroupBy(s => s.StepType)
                .ToDictionary(g => g.Key, g => g.Count());

            analysis["步骤类型分布"] = stepTypes;

            var keyStepsCount = withThinkingChain.Sum(r => r.ThinkingSteps.Count(s => s.IsKeyStep));
            analysis["关键步骤总数"] = keyStepsCount;
            analysis["关键步骤比例"] = keyStepsCount / (float)withThinkingChain.Sum(r => r.ThinkingSteps.Count) * 100;
        }

        return analysis;
    }

    private void UpdateStatistics(ThinkingChainResponse response)
    {
        _statistics.TotalResponses++;

        if (response.HasThinkingChain)
        {
            _statistics.ResponsesWithThinkingChain++;

            var totalSteps = _processedResponses.Where(r => r.HasThinkingChain).Sum(r => r.ThinkingSteps.Count) + response.ThinkingSteps.Count;
            _statistics.AverageThinkingSteps = totalSteps / (float)_statistics.ResponsesWithThinkingChain;

            if (response.ThinkingSteps.Count > _statistics.MaxThinkingSteps)
            {
                _statistics.MaxThinkingSteps = response.ThinkingSteps.Count;
            }

            var totalThinkingLength = _processedResponses.Where(r => r.HasThinkingChain).Sum(r => r.ThinkingChain.Length) + response.ThinkingChain.Length;
            var totalContentLength = _processedResponses.Sum(r => r.RawContent.Length) + response.RawContent.Length;
            _statistics.ThinkingChainRatio = totalThinkingLength / (float)totalContentLength * 100;
        }

        _statistics.LastUpdated = DateTime.Now;
    }
}
